package com.zs.mybatis.excutor;

import com.zs.mybatis.config.BoundSql;
import com.zs.mybatis.config.Configuration;
import com.zs.mybatis.config.MappedStatement;
import com.zs.mybatis.utils.GenericTokenParser;
import com.zs.mybatis.utils.ParameterMapping;
import com.zs.mybatis.utils.ParameterMappingTokenHandler;

import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class SimpleSqlExecutor implements SqlExecutor {

    //数据库连接
    private static volatile Connection connection =null;

    public <E> List<E> query(Configuration configuration, MappedStatement mappedStatement, Object[] param) throws SQLException, NoSuchFieldException, IllegalAccessException, InstantiationException, IntrospectionException, InvocationTargetException {
        //单例连接
        if (connection == null) {
            synchronized (this) {
                if (connection == null) {
                    try {
                        connection = configuration.getDataSource().getConnection();
                    } catch (SQLException throwables) {
                        throwables.printStackTrace();
                    }
                }

            }
        }
        //处理SQL
        BoundSql boundsql =getBoundSql(mappedStatement.getSql());
        String sqlText = boundsql.getSqlText();
        //预编译SQL
        PreparedStatement preparedStatement = connection.prepareStatement(sqlText);
        //参数填充
        Class<?> parameter = mappedStatement.getParameterType();
        List<ParameterMapping> parameterMappingList = boundsql.getParameterMappingList();
        //遍历的到的参数名称
        for (int i = 0; i < parameterMappingList.size(); i++) {
            ParameterMapping parameterMapping = parameterMappingList.get(i);
            //根据解析出参数名，通过反射获取参数
            Field declaredField = parameter.getDeclaredField(parameterMapping.getContent());
            //设置暴力反射
            declaredField.setAccessible(true);
            // TODO: 2021/11/6 未考虑多个参数的情况
            Object o = declaredField.get(param[0]);
            //依次给占位符
            preparedStatement.setObject(i+1,o);
        }
        ResultSet resultSet = preparedStatement.executeQuery();
        Class<?> resultType = mappedStatement.getResultType();
        List<E> list = new ArrayList<E>();
        while (resultSet.next()) {
            E o = null;
            //创建对象
            if (resultType != null) {
                o = (E) resultType.newInstance();
            }
            ResultSetMetaData metaData = resultSet.getMetaData();
            int columnCount = metaData.getColumnCount();
            //列以1开始
            for (int i = 1; i <= columnCount; i++) {
                //属性名
                String columnClassName = metaData.getColumnName(i);
                //属性值
                Object value = resultSet.getObject(columnClassName);
                //创建属性描述器，为属性⽣成读写⽅法
                PropertyDescriptor propertyDescriptor = new PropertyDescriptor(columnClassName, resultType);
                //获取写⽅法
                Method writeMethod = propertyDescriptor.getWriteMethod();
                writeMethod.invoke(o, value);
            }
            list.add(o);
        }
        return list;
    }

    /*
    * 关闭连接
    */
    public void close() {
        try {
            connection.close();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }

    private BoundSql getBoundSql(String sql) {
        //标记处理类：主要是配合通⽤标记解析器GenericTokenParser类完成对配置⽂件等的解析⼯作，其中TokenHandler主要完成处理
        ParameterMappingTokenHandler parameterMappingTokenHandler = new
                ParameterMappingTokenHandler();
        //GenericTokenParser :通⽤的标记解析器，完成了代码⽚段中的占位符的解析，然后再根据给定的标记处理器(TokenHandler)来进⾏表达式的处理
        //三个参数：分别为openToken (开始标记)、closeToken (结束标记)、handler (标记处 理器)
        GenericTokenParser genericTokenParser = new GenericTokenParser("#{",
                "}", parameterMappingTokenHandler);
        //解析后的SQL
        String parse = genericTokenParser.parse(sql);
        List<ParameterMapping> parameterMappings =
                parameterMappingTokenHandler.getParameterMappings();
        BoundSql boundSql = new BoundSql(parse, parameterMappings);
        return boundSql;
    }
}
